﻿using SmartForm.Common;
using SmartlForm.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions;
using Dapper;
using SmartForm.Util;

namespace SmartlForm.DAL
{
    public class KeywordDao
    {
        public readonly static KeywordDao Instance = new KeywordDao();
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="pageNo"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageHelper<Keyword> GetPageList(int pageNo, int pageSize, long accountId, string keyword)
        {
            var pageInfo = new PageHelper<Keyword>();
            var sql = string.Format("SELECT * FROM keyword WHERE account_id={0}", accountId);
            var where = string.Empty;
            if (!string.IsNullOrEmpty(keyword))
            {
                sql += string.Format("name LIKE '%{0}%'", keyword);
            }
            pageInfo.Data = DataBase.DB.Query<Keyword>(string.Format("{0} Limit @Take Offset @Skip", sql), new { Take = pageSize, Skip = (pageNo - 1) * pageSize }).AsList();
            pageInfo.Total = DataBase.DB.QueryFirstOrDefault<int>(string.Format("SELECT COUNT(1) FROM ({0})", sql));
            pageInfo.PageNo = pageNo;
            pageInfo.PageSize = pageSize;
            return pageInfo;
        }


        public long Add(string name, long account_id)
        {
            var model = new Keyword()
            {
                name = name,
                c_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                account_id = account_id,
            };
            long id = DataBase.DB.Insert(model);
            return id;
        }

        public Keyword Get(long id)
        {
            return DataBase.DB.QueryFirstOrDefault<Keyword>("SELECT * FROM keyword WHERE id=@id", new { id = id });
        }


        public Keyword GetByName(string name)
        {
            return DataBase.DB.QueryFirstOrDefault<Keyword>("SELECT * FROM keyword WHERE name=@name", new { name = name });
        }

        /// <summary>
        /// 删除关键词
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Del(long id)
        {
            return DataBase.DB.Execute("DELETE FROM keyword WHERE id=@id", new { id = id });
        }

        /// <summary>
        /// 获取任务下所有已启用的配置
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public List<Keyword> GetList(long accountId)
        {
            return DataBase.DB.Query<Keyword>("SELECT * FROM keyword WHERE account_id=@account_id", new { account_id = accountId }).AsList();
        }
    }
}
